﻿using PPIDesktopClient.Entities;
using PPIDesktopClient.General;
using PPIDesktopClient.Logic;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using VMind.Global;

namespace PPIDesktopClient
{
    public partial class frmPolygonQuery : frmDialogBase
    {
        #region Private Members
        private List<EUtility_Polygon> m_SelectedPolygons;
        private Int32 m_PolygonQueryId = Int32.MinValue;
        #endregion

        #region Public Properties
        public Int32 PolygonQueryId
        {
            get { return m_PolygonQueryId; }
            set { m_PolygonQueryId = value; }
        }
        #endregion

        public frmPolygonQuery()
        {
            InitializeComponent();
            txtFont.Font = dlgFont.Font;
            txtFont.Text = dlgFont.Font.Name + ", " + dlgFont.Font.Size.ToString() + "pt";
        }

        private void frmPolygonQuery_Load(object sender, EventArgs e)
        {
            m_SelectedPolygons = new List<EUtility_Polygon>();
            this.tbcPolygonQuery.SelectedTab = tbiCriteria;
            LoadCombos();
            DataTable _Dt = LUtility_Polygon.SelectAllTree();
            pgtCriteria.Polygons = new List<EUtility_Polygon>();
            foreach (DataRow _Dr in _Dt.Rows)
                pgtCriteria.Polygons.Add(new EUtility_Polygon(ConvertHelper.ToInt32(_Dr["Utility_PolygonId"]), ConvertHelper.Tostring(_Dr["Name"]), new EUtility_Polygon(ConvertHelper.ToInt32(_Dr["Utility_Polygon_ParentPolygonFk"]))));
            pgtCriteria.Refresh();
            if (m_PolygonQueryId != Int32.MinValue)
                LoadData();
        }

        private void LoadCombos()
        {
            DataTable _Dt = LUtility_Query_Type.SelectAllIdName();
            PPIDesktopClient.General.UIHelper.FillDropDown(ddlType, _Dt, "Name", "Utility_Query_TypeId", "Select an option...");
        }

        private void LoadData()
        {
            EUtility_QueryPolygon _Query = LUtility_QueryPolygon.SelectCRUD(m_PolygonQueryId);
            txtName.Text = _Query.Name;
            ddlType.SelectedIndex = PPIDesktopClient.General.UIHelper.GetItemIndex(ddlType, _Query.Utility_Query_Type.Utility_Query_TypeId.ToString());
            sldAltitude.Value = ConvertHelper.ToInt32(_Query.Altitude * 100);
            //FIXME: see if there's a better way to do this
            cpbLine.SelectedColor = System.Drawing.Color.FromArgb((_Query.LineColor - _Query.LineColor % 1000000) / 1000000, (_Query.LineColor % 1000000 - _Query.LineColor % 1000) / 1000, _Query.LineColor % 1000);
            sldWidth.Value = _Query.LineWidth;
            cpbFill.SelectedColor = System.Drawing.Color.FromArgb((_Query.FillColor - _Query.FillColor % 1000000) / 1000000, (_Query.FillColor % 1000000 - _Query.FillColor % 1000) / 1000, _Query.FillColor % 1000);
            sldOpacity.Value = _Query.FillOpacity;
            cpbFont.SelectedColor = System.Drawing.Color.FromArgb((_Query.FontColor - _Query.FontColor % 1000000) / 1000000, (_Query.FontColor % 1000000 - _Query.FontColor % 1000) / 1000, _Query.FontColor % 1000);
            dlgFont.Font = new System.Drawing.Font(_Query.Font, (float)8.25);
            txtFont.Font = dlgFont.Font;
            txtFont.Text = dlgFont.Font.Name + ", " + dlgFont.Font.Size.ToString() + "pt";
            chkPoints.Checked = _Query.Points;
            DataTable _Dt;
            m_SelectedPolygons.Clear();
            if (_Query.Points)
            {
                _Dt = LUtility_QueryPolygon_Point.SelectAllByQuery(m_PolygonQueryId);
                foreach (DataRow _Dr in _Dt.Rows)
                    lstPoints.Items.Add(ConvertHelper.Todouble(_Dr["Latitude"]).ToString() + ", " + ConvertHelper.Todouble(_Dr["Longitude"]).ToString());
            }
            else
            {
                List<Int32> _SelectedIds = new List<Int32>();
                _Dt = LUtility_Polygon.SelectAllByQuery(m_PolygonQueryId);
                foreach (DataRow _Dr in _Dt.Rows)
                    _SelectedIds.Add(ConvertHelper.ToInt32(_Dr["Utility_PolygonFk"]));
                pgtCriteria.SelectPolygons(_SelectedIds);
                lstPoints.Items.Clear();
            }
        }

        private void chkPoints_CheckedChanged(object sender, EventArgs e)
        {
            RFV_pgtCriteria.Enabled = !chkPoints.Checked;
            RFV_pgtCriteria.Visible = false;
            tbiCriteria.Visible = !chkPoints.Checked;
            RFV_lstPoints.Enabled = chkPoints.Checked;
            RFV_lstPoints.Visible = false;
            txtLatitude.Enabled = chkPoints.Checked;
            txtLongitude.Enabled = chkPoints.Checked;
            lstPoints.Enabled = chkPoints.Checked;
            btnAdd.Enabled = chkPoints.Checked;
            btnRemove.Enabled = chkPoints.Checked && lstPoints.SelectedIndex > -1;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            VAL_txtLatitude.Enabled = true;
            VAL_txtLongitude.Enabled = true;
            VAL_txtLatitude.Validate();
            VAL_txtLongitude.Validate();
            if (VAL_txtLatitude.IsValid && VAL_txtLongitude.IsValid)
                lstPoints.Items.Add(ConvertHelper.Todouble(txtLatitude.Text).ToString() + ", " + ConvertHelper.Todouble(txtLongitude.Text).ToString());
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (lstPoints.SelectedIndex > -1)
                lstPoints.Items.RemoveAt(lstPoints.SelectedIndex);
            btnRemove.Enabled = lstPoints.SelectedIndex > -1;
        }

        private void lstPoint_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnRemove.Enabled = lstPoints.SelectedIndex > -1;
        }

        private void sldAltitude_ValueChanged(object sender, EventArgs e)
        {
            lblAltitude.Text = (Convert.ToDouble(sldAltitude.Value) / 100).ToString("F2");
        }

        private void btnFont_Click(object sender, EventArgs e)
        {
            dlgFont.ShowDialog();
            txtFont.Font = dlgFont.Font;
            txtFont.Text = dlgFont.Font.Name + ", " + dlgFont.Font.Size.ToString() + "pt";
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            VAL_txtLatitude.Enabled = false;
            VAL_txtLongitude.Enabled = false;
            VAL_txtLatitude.Visible = false;
            VAL_txtLongitude.Visible = false;
            RFV_pgtCriteria.Visible = RFV_pgtCriteria.Enabled && m_SelectedPolygons.Count <= 0;
            RFV_pgtCriteria.Tag = RFV_pgtCriteria.Enabled && m_SelectedPolygons.Count <= 0;
            RFV_lstPoints.Visible = RFV_lstPoints.Enabled && lstPoints.Items.Count < 3;
            RFV_lstPoints.Tag = RFV_lstPoints.Enabled && lstPoints.Items.Count < 3;
            if (ValidateAll() && !(bool)RFV_lstPoints.Tag && !(bool)RFV_pgtCriteria.Tag)
            {
                EUtility_QueryPolygon _Query = new EUtility_QueryPolygon();
                _Query.Utility_QueryPolygonId = m_PolygonQueryId;
                _Query.Name = txtName.Text;
                _Query.Utility_Query_Type = new EUtility_Query_Type(Convert.ToInt32(((ListBoxItem)ddlType.SelectedItem).Value));
                _Query.Altitude = Convert.ToDouble(sldAltitude.Value) / 100;
                //FIXME: see if there's a better way to do this
                _Query.LineColor = cpbLine.SelectedColor.R * 1000000 + cpbLine.SelectedColor.G * 1000 + cpbLine.SelectedColor.B;
                _Query.LineWidth = sldWidth.Value;
                _Query.FillColor = cpbFill.SelectedColor.R * 1000000 + cpbFill.SelectedColor.G * 1000 + cpbFill.SelectedColor.B;
                _Query.FillOpacity = sldOpacity.Value;
                _Query.FontColor = cpbFont.SelectedColor.R * 1000000 + cpbFont.SelectedColor.G * 1000 + cpbFont.SelectedColor.B;
                _Query.Font = dlgFont.Font.Name;
                _Query.Points = chkPoints.Checked;
                if (chkPoints.Checked)
                {
                    _Query.Utility_QueryPolygon_Points = new EUtility_QueryPolygon_Point[lstPoints.Items.Count];
                    for (Int32 _I = 0; _I < lstPoints.Items.Count; _I++)
                        _Query.Utility_QueryPolygon_Points[_I] = new EUtility_QueryPolygon_Point(Int32.MinValue, new EUtility_QueryPolygon(_Query.Utility_QueryPolygonId), ConvertHelper.Todouble(lstPoints.Items[_I].ToString().Substring(0, lstPoints.Items[_I].ToString().IndexOf(','))), ConvertHelper.Todouble(lstPoints.Items[_I].ToString().Substring(lstPoints.Items[_I].ToString().IndexOf(',') + 2, lstPoints.Items[_I].ToString().Length - lstPoints.Items[_I].ToString().IndexOf(',') - 2)));
                    _Query.Utility_Polygons = new EUtility_Polygon[0];
                }
                else
                {
                    _Query.Utility_Polygons = m_SelectedPolygons.ToArray();
                    _Query.Utility_QueryPolygon_Points = new EUtility_QueryPolygon_Point[0];
                }

                this.DialogResult = DialogResult.OK;
                LUtility_QueryPolygon.Save(_Query);
                MessageBox.Show("The Polygon Query " + _Query.Utility_QueryPolygonId.ToString() + " has been saved succesfully");
                this.Close();
            }
            else if ((bool)RFV_lstPoints.Tag || !ValidateAll())
                tbcPolygonQuery.SelectedTab = tbiSetup;
            else
                tbcPolygonQuery.SelectedTab = tbiCriteria;
        }

        private void pgtCriteria_CheckedChange(object sender, TreeViewEventArgs e)
        {
            EUtility_Polygon polygon = (EUtility_Polygon)sender;
            if (e.Node.Checked && !m_SelectedPolygons.Contains(polygon))
                m_SelectedPolygons.Add(polygon);
            else if (!e.Node.Checked && m_SelectedPolygons.Contains(polygon))
                m_SelectedPolygons.Remove(polygon);
        }
    }
}
